package com.bright.ghj.common.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;

@Component
public class MybatisMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        insertOrUpdateFill(metaObject, true);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        insertOrUpdateFill(metaObject, false);
    }

    private void insertOrUpdateFill(MetaObject metaObject, boolean isInsert) {
        if (isInsert) {
            if (Objects.isNull(getFieldValByName("createDate",metaObject)))
                this.setFieldValByName("createDate", LocalDateTime.now(), metaObject);
            this.setFieldValByName("deleted", 0, metaObject);
        } else {
            if (Objects.isNull(getFieldValByName("writeDate",metaObject)))
                this.setFieldValByName("writeDate", LocalDateTime.now(), metaObject);
        }
    }
}

